package com.qf.web.controller;/*
*王浩政 
*
2022/8/18
22:34
*小米商城
*/

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("utf-8");
        String methodName=req.getParameter("method");
        //反射 类对象
        try {

            Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            if(method!=null){
                String url =(String) method.invoke(this, req, resp);//null "index.jsp" "redirect:/index.jsp"
                if(url==null||url.trim().length()==0){
                    return ;//结束方法
                }
                //转发重定向
                if (url.startsWith("redirect:")){//重定向
                    String redirectURL=url.substring(url.indexOf(":")+1);///index.jsp
                    resp.sendRedirect(req.getContextPath()+redirectURL);//index.jsp
                }else {//转发
                    req.getRequestDispatcher(url).forward(req,resp);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
